// @ts-nocheck

export const iframeFunCallExpose = (fnMap = {}) => {
    const w = window;
    const topWindow = window.top;
  
    let listen;
    w.addEventListener(
      'message',
      (listen = (e) => {
        const { type, iframeName } = e.data;
  
        if (!iframeName || iframeName !== window.name) {
          return;
        }
  
        if (type === 'fn-call') {
          const { fn, args, uid } = e.data;
  
          const fnCall = fnMap[fn];
  
          if (!fnCall) {
            topWindow.postMessage(
              {
                type: 'fn-ret',
                uid,
                error: new Error(`${fn} 函数不存在`),
              },
              '*'
            );
            return;
          }
  
          if (!uid) {
            return;
          }
  
          (async () => {
            topWindow.postMessage(
              {
                type: 'fn-call-start',
                uid,
              },
              '*'
            );
  
            try {
              const result = await fnCall(...args);
              topWindow.postMessage(
                {
                  type: 'fn-ret',
                  uid,
                  result,
                },
                '*'
              );
            } catch (error) {
              console.error(error);
              topWindow.postMessage(
                {
                  type: 'fn-ret',
                  uid,
                  error: new Error(`${fn} 执行报错: ${error.message}`),
                },
                '*'
              );
            }
          })();
        }
      })
    );
  
    return () => {
      w.removeEventListener('message', listen);
      return fnMap;
    };
  };
  
//   window.iframeFunCallExpose = iframeFunCallExpose;
  